package com.esyoga.yoyoga.util;

import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class WebSocketUtil {

    //存放当前在聊天室中的人,下面map为线程安全的
    public static final Map<String, Session> SESSIONMAP=new ConcurrentHashMap<>();
    //发送数据的方法:指定向某一个客户端发送消息
    public static void sendMessage(Session session,String message){
        if(session!=null){
            final RemoteEndpoint.Basic basic=session.getBasicRemote();
            if(basic!=null){
                try {
                    basic.sendText(message);//向客户端发送消息
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    //发给所有人:遍历map
    public static void sendAll(String message){
        //传统方法
		/*Iterator<String> iterator=SESSIONMAP.keySet().iterator();
		while(iterator.hasNext()){
			String sessionId=iterator.next();
			Session session=SESSIONMAP.get(sessionId);
			sendMessage(session, message);
		}*/
        //java1.8新特性
        SESSIONMAP.forEach((sessionId,session)->sendMessage(session, message));
    }

}
